<template>
	<div style="justify-content: center; align-items: center" display="flex">
		<div id="self_defined_element"></div>
		<div style="text-align: center; margin-top: 30px">请使用钉钉扫码登录</div>
	</div>
</template>

<script lang="ts" setup>
import { onMounted, computed, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { clearTokens } from '/@/utils/axios-utils';
import { getUserInfo } from '/@/api/user';
import { Session } from '/@/utils/storage';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import cache from '/@/utils/hook/cache';
import { formatAxis } from '/@/utils/formatTime';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { NextLoading } from '/@/utils/loading';

const router = useRouter();
const route = useRoute();
const { t } = useI18n();
onMounted(() => {
	//重定向回首页后,在请求authCode
	if (Session.get('authCode')) {
		loadAuthCode({ authCode: Session.get('authCode') });
	}
	loginAction();
});

const loginAction = () => {
	//钉钉扫码登录API
	window.DTFrameLogin(
		{
			id: 'self_defined_element',
			width: 400,
			height: 255,
		},
		{
			redirect_uri: encodeURIComponent(`${window.$formalHost}login`),
			// client_id: 'dingbhhi8hdwbbdagitk',
			client_id: 'dingbcm6r33dmvfvxjrp',
			scope: 'openid',
			response_type: 'code',
			state: 'state',
			prompt: 'consent',
		},
		(loginResult: any) => {
			const { redirectUrl, authCode, state } = loginResult;
			window.location.href = redirectUrl;
			//防止重定向后,vue销毁
			Session.set('authCode', authCode);
			// 这里可以直接进行重定向
			NextLoading.start();
		},
		(errorMsg: any) => {
			ElMessage.error(`${errorMsg}`);
			Session.set('isShowScan', "true");
			window.location.reload();

			// 这里一般需要展示登录失败的具体原因
			// alert(`Login Error: ${errorMsg}`);
		}
	);
};

//通过autoCode获取token
const loadAuthCode = (params: any) => {
	clearTokens();
	axios.defaults.baseURL = window.$host;
	axios
		.get('/api/dingLogin', {
			params,
		})
		.then(async (res) => {
			Session.remove('authCode');
			if (res.data.code == 200) {
				NextLoading.done();
				// 添加完动态路由再进行router跳转，否则可能报错 No match found for location with path "/"
				await initBackEndControlRoutes();
				let userRes = await getUserInfo();
				//将用户信息保存
				cache.setCache('userInfo', userRes.data.loginEmpInfo);
				Session.set('path', 'login');
				if (Session.get('token')) {
				// 再执行 signInSuccess
				signInSuccess();
			} else {	
				// router.push('/login');
				alert('请联系管理员添加用户菜单权限');
			}
			} else {
				Session.set('token', res.data.data);
				NextLoading.done(500);
			}
		})
		.catch((error) => {
			Session.remove('authCode');
		});
};
// 时间获取
const currentTime = computed(() => {
	return formatAxis(new Date());
});
// 登录成功后的跳转
const signInSuccess = () => {
	// 初始化登录成功时间问候语
	let currentTimeInfo = currentTime.value;
	// 登录成功跳到转首页，如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
	if (route.query?.redirect) {
		router.push({
			path: <string>route.query?.redirect,
			query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
		});
	} else {
		router.push('/');
	}
	const signInText = t('signInText');
	ElMessage.success(`${currentTimeInfo}, ${signInText}`);
	// 添加loading，防止第一次进入界面时出现短暂空白
	NextLoading.start();
};
</script>

<style scoped lang="scss"></style>
